package edu.yzu.testspringboot002.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;

import edu.yzu.testspringboot002.exception.BizException;
import edu.yzu.testspringboot002.po.FileVO;
import edu.yzu.testspringboot002.service.impl.UploadService;
import edu.yzu.testspringboot002.utils.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 常见控制器
 *
 * @author yulang
 * @date 2023-08-21
 */
@RestController
@RequestMapping("/wechat/client")
@Slf4j(topic = "CommonController")
public class CommonController {



    //图片资源访问路径
    static String fileLocation = "/restaurantRes";


    @Value("${file.path:}")
    private String fileLocationPath;


    @Autowired
    private UploadService uploadService;


    public String getUploadPath(HttpServletRequest request, String fileName) {
        // http://127.0.0.1:7877/chat/restaurantRes/restaurantRes/9e2357a623354d3693272536702ee267.png
        // http://127.0.0.1:7877//chat//restaurantRes/5b58573126c34d88b73413a076463e09/5b58573126c34d88b73413a076463e09.png
        //http://127.0.0.1:7877//chat//restaurantRes//restaurantRes/d1c57211afdf4ec48fec6b7cebe944ab.png
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + fileLocation + "/" + fileName;
    }

    @PostMapping("/upload")
    public ResponseResult<FileVO> uploadFile(@RequestParam("file") MultipartFile multipartFile,
                                             @RequestParam(value = "sendId",
                                                     required = false) String sendId,
                                             @RequestParam(value = "groupId", required = false)
                                                 String groupId)  {

        String originalFilename = multipartFile.getOriginalFilename();

        long fileSize = multipartFile.getSize();
        if (fileSize > 1024 * 1024 * 10) {
            throw new BizException("文件大小超过10M,暂时不支持上传！");
        }
        String extName = FileUtil.extName(originalFilename);

        String fileName = UUID.fastUUID().toString().replaceAll("-", "");

        String newFileName = fileName + "." + extName;

        String uploadPathUrl = null;
        try {
            uploadPathUrl = uploadService.uploadFile(multipartFile.getInputStream(), fileSize, multipartFile.getContentType(), newFileName);
            return ResponseResult.ok(new FileVO(uploadPathUrl, extName, originalFilename));
        } catch (IOException e) {
            return ResponseResult.failed(e.getMessage());
        }

    }










}
